<template>
  <BaseDialog
    :visible="visible"
    :title="title || (isEditMode ? '编辑流媒体服务器' : '添加流媒体服务器')"
    width="500px"
    footer-type="default"
    :confirm-loading="loading"
    @update:visible="$emit('update:visible', $event)"
    @close="$emit('close')"
    @cancel="$emit('close')"
    @confirm="handleSave"
  >
    <el-form :model="formData" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="服务器名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入服务器名称" />
      </el-form-item>
      <el-form-item label="IP地址" prop="ip" v-if="!isEditMode">
        <el-input v-model="formData.ip" placeholder="请输入IP地址" />
      </el-form-item>
      <el-form-item label="端口" prop="port" v-if="!isEditMode">
        <el-input-number v-model="formData.port" :min="1" :max="65535" />
      </el-form-item>
      <el-form-item label="用户名" prop="username" v-if="!isEditMode">
        <el-input 
          v-model="formData.username" 
          placeholder="请输入用户名" 
          autocomplete="off"
        />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!isEditMode">
        <el-input 
          v-model="formData.password" 
          type="password" 
          placeholder="请输入密码" 
          autocomplete="new-password"
        />
      </el-form-item>
    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { ElForm, ElFormItem, ElInput, ElInputNumber } from 'element-plus'
import type { StreamServer } from '../../../../types'

// Props
interface Props {
  visible: boolean
  isEditMode: boolean
  serverData?: StreamServer | null
  title?: string
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'close': []
  'save': [data: Partial<StreamServer>]
  'update:visible': [value: boolean]
}>()

// 表单数据
const formData = reactive({
  id: null as number | null,
  name: '',
  ip: '',
  port: 40000,
  username: 'admin',
  password: 'admin'
})

// IP地址验证函数
const validateIP = (_rule: any, value: string, callback: any) => {
  const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
  if (!value) {
    callback(new Error('请输入IP地址'))
  } else if (!ipRegex.test(value)) {
    callback(new Error('请输入正确的IP地址格式'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入服务器名称', trigger: 'blur' }],
  ip: [{ required: true, validator: validateIP, trigger: 'blur' }],
  port: [{ required: true, message: '请输入端口', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()

// Loading 状态
const loading = ref(false)

// 监听props变化，更新表单数据
watch(() => props.serverData, (newData) => {
  if (newData) {
    // 安全地更新表单数据，确保所有字段都被正确设置
    formData.id = newData.id || null
    formData.name = newData.name || ''
    formData.ip = newData.ip || ''
    formData.port = String(newData.port || '')
    // 后端返回的是 userName，需要映射到 username
    formData.username = (newData as any).userName || newData.username || ''
    formData.password = newData.password || ''
  } else {
    // 重置表单
    Object.assign(formData, {
      id: null,
      name: '',
      ip: '',
      port: 40000,
      username: 'admin',
      password: 'admin'
    })
  }
}, { immediate: true })

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    
    // 处理数据格式
    const saveData: any = {
      name: formData.name,
      ip: formData.ip,
      port: Number(formData.port),
      username: formData.username,
      password: formData.password
    }
    
    // 编辑模式时才添加 id 字段
    if (props.isEditMode && formData.id) {
      saveData.id = formData.id
    }
    
    // 设置 loading 状态
    loading.value = true
    
    emit('save', saveData)
    
    // 注意：这里不关闭对话框，让父组件处理成功后关闭
  } catch (error) {
    console.error('表单验证失败:', error)
    loading.value = false
  }
}

// 重置 loading 状态的方法
const resetLoading = () => {
  loading.value = false
}

// 暴露方法给父组件
defineExpose({
  resetLoading
})
</script>

<style scoped>
/* 组件样式可以在这里添加 */
</style>
